package com.mingda.weathermagiccenter.config;

import com.mingda.weathermagiccenter.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.interceptor.RequestInterceptor;
import org.ssssssss.magicapi.core.model.ApiInfo;
import org.ssssssss.magicapi.core.model.JsonBean;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletRequest;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletResponse;
import org.ssssssss.script.MagicScriptContext;

/**
 * magic-api 接口鉴权
 */
@Component
public class CustomRequestInterceptor implements RequestInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(CustomRequestInterceptor.class);


    @Value("${magic-api.tokenenable:false}")
    private String usetoken;
    /**
     * 接口请求之前
     * @param info	接口信息
     * @param context	脚本变量信息
     */
    @Override
    public Object preHandle(ApiInfo info, MagicScriptContext context, MagicHttpServletRequest request, MagicHttpServletResponse response) throws Exception {
        //  User user = null; // = XXXUtils.getUser(request);
        logger.info("{} 请求接口：{}", null, info.getName());
        if("false".equals(usetoken)){
            return null;
        }
        boolean  flag =  isLoginAttempt(request,response);
        // 接口选项配置了需要登录
            if (!flag) {
                return new JsonBean<>(401, "无权访问,请使用token访问");
            }
        boolean vflag = executeLogin(request,response);
        // 接口选项配置了需要登录
         if (!vflag) {
             return new JsonBean<>(401, "无权访问,token不合法");
          }
        return null;
    }

    /**
     * 接口执行之后
     * @param info	接口信息
     * @param context	变量信息
     * @param value 即将要返回到页面的值
     */
    @Override
    public Object postHandle(ApiInfo info, MagicScriptContext context, Object value, MagicHttpServletRequest request, MagicHttpServletResponse response) throws Exception {
        logger.info("{} 执行完毕，返回结果:{}", info.getName(), value);
        return null;
    }


    /**
     * 判断用户是否想要登入。 检测header里面是否包含Authorization字段即可
     */
    protected boolean isLoginAttempt(MagicHttpServletRequest request, MagicHttpServletResponse response) {
        String authorization = request.getHeader("Authorization");
        String authorization2 = request.getHeader("APIToken");
        return authorization != null || authorization2 != null;
    }

    /**
     * 执行登录流程
     */
    protected boolean executeLogin(MagicHttpServletRequest request, MagicHttpServletResponse response) throws Exception {

        String authorization = request.getHeader("Authorization");
        String authorization2 = request.getHeader("APIToken"); //备用 web用
        String token = "";
        if(!StringUtils.isBlank(authorization2)){
            token = authorization2;
        }
        else{
            token = authorization;
        }
        try {
            JwtUtil jwtUtil = new JwtUtil();
            if (!jwtUtil.isVerify(token)) {
                logger.info("{} token验证失败，token:{}", token);
                return false;
            }
        } catch (Exception e) {
            logger.error("{} token验证失败，token:{}", token);
           return false;
         }
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }



}